package service;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import serviceInterface.UserServiceInterface;
import domain.Driver;
import domain.Person;

@Stateless
public class UserService implements UserServiceInterface{
	
	@PersistenceContext
	private EntityManager entityManager;
	
	public Person login(Person p){
		Person loginPerson = null;
			try {
				p.encodePassword();
				Query query = entityManager.createQuery("SELECT p FROM Person AS p WHERE p.userName=:name and p.password=:pass");
				query.setParameter("name", p.getUserName());
				query.setParameter("pass", p.getPassword());
		        List<Person> persons = query.getResultList();
		        if(persons.size()==1){
		        	loginPerson = persons.get(0);
		        }
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return loginPerson;
	}
	
	@Override
	public List<Person> getAllDriver() {
		List<Person> drivers = new ArrayList<Person>();
		try{
			Query query = entityManager.createQuery("SELECT p FROM Person AS p ");
			
			List<Person> people = query.getResultList();
			for(Person p: people){
				Object role = p.getRoles().get(0);
				if(role instanceof Driver){
					drivers.add(p);
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return drivers;
	}
}
